package com.ai.controller.task;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import com.ai.common.model.Result;
import com.ai.common.utils.lang.json.JsonUtils;


@Controller
public class InfoRedisController {
	@Value("${redis.url}")
	private String redisUrl;
	
	
	private Log log = LogFactory.getLog(getClass());
	
	@RequestMapping("/info/initInfoRedis")
	public String initInfoRedis(HttpServletRequest request){
		try {
			String url = redisUrl.split(":")[0];
			String port = redisUrl.split(":")[1];
			request.setAttribute("url", url);
			request.setAttribute("port", Integer.valueOf(port));
		} catch (Exception e) {
			log.error("获取redis.url 异常："+e);
		}
		
		return "/task/infoRedisManage";
	}
	
	@SuppressWarnings("resource")
	@ResponseBody
    @RequestMapping("/info/queryRedis")
    public Result queryRedis(String host , int port , String key){
    	Result result = new Result();
    	try {
    		Jedis jedis = new Jedis(host , port );
    		boolean flag = jedis.exists(key);
        	if(flag){
        		String type = jedis.type(key);
        		/**
        		 * none (key不存在)
					string (字符串)
					list (列表)
					set (集合)
					zset (有序集)
					hash (哈希表)
        		 */
        		if("string".equalsIgnoreCase(type)){
        			String json = jedis.get(key);
            		if(StringUtils.isNotBlank(json)){
            			result.addAttribute("resultData", json);
            		}
        		}else if("list".equalsIgnoreCase(type)){
        			List<String> lrange = jedis.lrange(key, 0, jedis.llen(key));
        			result.addAttribute("resultData", JsonUtils.toJson(lrange));
        		} else if("set".equalsIgnoreCase(type)){
        			Set<String> smembers = jedis.smembers(key);
        			result.addAttribute("resultData", JsonUtils.toJson(smembers));
        		} else if("zset".equalsIgnoreCase(type)){
        			Set<Tuple> zrangeWithScores = jedis.zrangeWithScores(key, 0L, -1L);
        			result.addAttribute("resultData", JsonUtils.toJson(zrangeWithScores));
        		}else {
        			Map<String, String> map = jedis.hgetAll(key);
        			result.addAttribute("resultData", JsonUtils.toJson(map));
        		}
        	}else{
        		result.addAttribute("resultData", "null");
        	}
        	result.setSuccess(true);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(e.getMessage());
		}
    	return result;
    }
    
    @SuppressWarnings("resource")
	@ResponseBody
    @RequestMapping("/info/clearRedis")
    public Result clearRedis(String host , int port  , String key){
    	Result result = new Result();
    	try {
    		Jedis jedis = new Jedis(host , port );
    		boolean flag = jedis.exists(key);
        	if(flag){
        		jedis.del(key);
        	}
        	result.setSuccess(true);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(e.getMessage());
		}
    	return result;
    }

	@SuppressWarnings("resource")
	@ResponseBody
    @RequestMapping("/info/getAllKeys")
    public Result getAllKeys(String host , int port ,String key){
    	Result result = new Result();
    	try {
    		Jedis jedis = new Jedis(host , port );
			Set<String> keys = jedis.keys(key);
			if(!keys.isEmpty()){
				StringBuffer sb = new StringBuffer();
				for(String strs : keys ){
					sb.append("<a href=\"javascript:void(0);\" onclick=\"queryRedis('"+strs+"');\">").append(strs).append("</a>").append("<br />");
				}
				result.addAttribute("resultData", sb.toString());
			}else{
				result.addAttribute("resultData", "没有相同关联的keys");
			}
        	result.setSuccess(true);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(e.getMessage());
		}
    	return result;
    }
	
}
